﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Threading;
using UmengAnalyticsNet.Interface;
using UmengSDK;

namespace UmengAnalyticsNet.Wpf
{
    public class UmengAnalyticsApp : IAnalyticsApplication
    {
        private IAppHandler _handler;
        private bool _initialized;

        public static void Initialize(string appkey, string channel = "Marketplace")
        {
            UmengAnalytics.Initialize(appkey, new AppInfo(), new UmengAnalyticsApp(), channel);
        }

        public bool RegisterEvents(IAppHandler p_handler)
        {
            _handler = p_handler;

            var app = Application.Current;
            bool result = false;
            do
            {
                if (app == null)
                {
                    break;
                }

                try
                {
                    if (!_initialized)
                    {
                        _initialized = true;
                        p_handler.Launching();
                    }
                    //app.Startup += OnStartup;
                    app.Exit += OnExit;
                    app.DispatcherUnhandledException += OnDispatcherUnhandledException;
                    result = true;
                }
                catch
                {
                    break;
                }

            } while (false);

            return result;
        }

        private void OnExit(object sender, ExitEventArgs e)
        {
            try
            {
                if (_handler != null)
                {
                    _handler.Pause();
                }
            }
            catch (Exception)
            {
                //
            }
        }

        private void OnStartup(object sender, StartupEventArgs e)
        {
            try
            {
                if (_handler != null)
                {
                    _handler.Launching();
                }
            }
            catch (Exception)
            {
                //
            }
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                if (_handler != null)
                {
                    _handler.UnhandledException(e.Exception);
                }
            }
            catch (Exception)
            {
                //
            }
        }
    }
}